package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.sub.impl20140402.v3.anacojp.AnaCoJpInernationRoundTrip;
import com.foreveross.crawl.common.exception.self.SourceDataParseNullException;
import com.foreveross.crawl.common.exception.self.UnableParseRouteTypeException;
import com.foreveross.crawl.domain.airfreight.doub.CabinRelationEntity;
import com.foreveross.crawl.domain.airfreight.doub.DoublePlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnDoublePlaneInfoEntity;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair;

/**
 * 全日空航空公司
 * @author luofangyi
 *
 */
public class AnaCoJpAdapter extends AbstractAdapter {

	public AnaCoJpAdapter(TaskModel taskQueue) {
		super(taskQueue);
	}

	@Override
	@Deprecated
	public String getUrl() throws Exception {
		
		return null;
	}

	@Override
	public Object fetch(String url) throws Exception {
		switch (getRouteType()) {
		case DOMESTIC_ONEWAYTRIP:
			throw new UnableParseRouteTypeException(taskQueue,getRouteType().getName());
		case DOMESTIC_ROUNDTRIP:
			throw new UnableParseRouteTypeException(taskQueue,getRouteType().getName());
		case INTERNATIONAL_ONEWAY:
			throw new UnableParseRouteTypeException(taskQueue, getRouteType().getName());
		case INTERNATIONAL_ROUND:
			return new AnaCoJpInernationRoundTrip(this, taskQueue).fetchData();
		}
		return null;
	}

	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		if(fetchObject == null){
			throw new SourceDataParseNullException("没有抓取到数据");
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		return (List<Object>)fetchObject;
	}
	
	public WebRequest getWebRequest(String url, HttpMethod method, List<NameValuePair> params) throws MalformedURLException{
		
		WebRequest webRequest = new WebRequest(new URL(url), method);
		webRequest.setRequestParameters(params);
		return webRequest;
	}
	
	/**
	 * 返回被选择radio的ID值
	 * @param html
	 * @param xPath
	 * @return
	 * @throws XPatherException
	 */
	public String getIdByCheckedRadio(String html, String xPath) throws XPatherException{
		Object[] inputs = parseOutputResults(html, xPath);
		String id = "";
		for (Object input : inputs) {
			TagNode node = (TagNode) input;
			if (!StringUtils.isBlank(node.getAttributeByName("checked"))) {
				id = node.getAttributeByName("id");
				break;
			}
		}
		return id;
	}
	
	public String getActionOfForm(String html, String xPath) throws XPatherException{
		Object[] inputs = parseOutputResults(html, xPath);
		String retStr = "";
		for(Object input : inputs){
			TagNode node = (TagNode) input;
			if (!StringUtils.isBlank(node.getAttributeByName("action"))) {
				retStr = node.getAttributeByName("action");
				break;
			} 
		}
		return retStr;
	}

	private Object[] parseOutputResults(String html, String xPath)
			throws XPatherException {
		HtmlCleaner cleaner = new HtmlCleaner();
		TagNode root = cleaner.clean(html);
		Object[] inputs = root.evaluateXPath(xPath);
		return inputs;
	}
	
	public String getPatternString(String content, String regEx){
		Pattern p=Pattern.compile(regEx, Pattern.DOTALL|Pattern.MULTILINE);
		Matcher m=p.matcher(content);
		String retStr = "";
		if(m.find()){
			retStr=  m.group(1);
		}
		return retStr.trim().replaceAll("\t", "").replaceAll("\n", "");
	}
	
	public String getPatternString(String content, String regEx, int step){
		Pattern p=Pattern.compile(regEx, Pattern.DOTALL|Pattern.MULTILINE);
		Matcher m=p.matcher(content);
		String retStr = "";
		boolean flag = false;
		for(int i = 0; i <= step; i ++){
			flag = m.find();
		}
		if(flag)
			retStr = m.group(1);
		return retStr.trim().replaceAll("&nbsp;", "").replaceAll("\t", "").replaceAll("\n", "");
	}
	
	/**  
	 * @Description: TODO
	 * @param @param content
	 * @param @param regEx
	 * @param @param replace 需替换字符
	 * @param @param replacement 指定的替换字符
	 * @param @return 
	 * @return List<String>
	 * @author luofangyi
	 * @date 2014-5-13 下午4:49:32 
	 */ 
	public List<String> getPatternList(String content, String regEx, String replace, String replacement){
		Pattern p=Pattern.compile(regEx, Pattern.DOTALL|Pattern.MULTILINE);
		Matcher m=p.matcher(content);
		List<String> strList = new ArrayList<String>();
		while(m.find()){
			strList.add(m.group(1).trim().replaceAll(replace, replacement));
		}
		return strList;
	}
	
	public List<DoublePlaneInfoEntity> dealToEntityAndReturnEntity(List<DoublePlaneInfoEntity> toEntity, List<ReturnDoublePlaneInfoEntity> returnEntity, String sumLowestPrice, String totalLowestPrice, String totalLowestTaxesPrice){
		
		int total = returnEntity.size() - 1;
		int currentStep = total;
		List<DoublePlaneInfoEntity> retList = new ArrayList<DoublePlaneInfoEntity>();
		int i = returnEntity.size() - 1;
		for(DoublePlaneInfoEntity to : toEntity){
			CabinRelationEntity relationEntity = new CabinRelationEntity();
			relationEntity.setCabinId(to.getCabins().iterator().next().getId());
			relationEntity.setFullPrice(Double.parseDouble(totalLowestPrice));
			relationEntity.setTotalFullPrice(Double.parseDouble(sumLowestPrice));
			relationEntity.setTaxesPrice(Double.parseDouble(totalLowestTaxesPrice));
			ReturnDoublePlaneInfoEntity ret = null;
			do{
				ret = returnEntity.get(i);
				relationEntity.setReturnCabinId(ret.getReturnCabins().iterator().next().getId());
				to.getCabinRelations().add(relationEntity);
				to.getReturnPlaneInfos().add(ret);
				i--;
				if(to.getFromCityName() != null && (to.getFromCityName() == ret.getToCityName())){
					break;
				}
			} while(i > 0 && ret != null && (to.getToCityName() != null && to.getToCityName() == ret.getFromCityName()));
			retList.add(to);
		}
		return retList;
	}
	
	/**
	 * 时分格式（HH:mm 或  HH时mm分）的时间格式转换成毫秒
	 * @param timeStr
	 * @return
	 */
	public Long timeToLong(String timeStr){
		
		Long time = null;
		Pattern pattern = Pattern.compile("\\d+");
		Matcher matcher = pattern.matcher(timeStr);
		List<String> timeList = new ArrayList<String>();
		while (matcher.find()) {
			timeList.add(matcher.group(0));
		}
		if(timeList.size() == 1){
			time = Long.parseLong(timeList.get(0)) * 60 * 1000;//分
		} else if(timeList.size() == 2){
			time = Long.parseLong(timeList.get(0)) * 60 * 60 * 1000;//时
			time += Long.parseLong(timeList.get(1)) * 60 * 1000;//分
		}
		return time;
	}
	
	public static void main(String[] args) throws Exception{
		TaskModel taskQueue = new TaskModel();
		taskQueue.setIsInternational(1);
		taskQueue.setIsReturn(1);
		taskQueue.setProxyIp("1");
//		taskQueue.setFlightDate("30/09/14");
//		taskQueue.setReturnGrabDate("29/10/14");
		taskQueue.setFlightDate("2014-10-03");
		taskQueue.setReturnGrabDate("2014-10-29");
		taskQueue.setIsInternational(1);
		taskQueue.setIsReturn(1);
		taskQueue.setFromCityName("北京");
		taskQueue.setFromCity("PEK");
//		taskQueue.setToCityName("华盛顿");
//		taskQueue.setToCity("IAD");
		taskQueue.setToCityName("纽约");
		taskQueue.setToCity("JFK");
//		taskQueue.setToCityName("旧金山");
//		taskQueue.setToCity("SFO");
		AnaCoJpAdapter round = new AnaCoJpAdapter(taskQueue);
		List<Object> objList = round.paraseToVo(round.fetch(null));
		round.printJson(objList, "f:/ana.txt");
	}

}
